<?php
/**
 * SchemaGenerator Class
 */


/**
 * Generate a basic schema for the selected database
 */
class SchemaGenerator
{

  public function generate($dbName)
  {
    $pdo = BenderDatabase::getPDO();
    $query = "SHOW FULL TABLES";
    $st =  $pdo->query($query);
    if($st === FALSE)
       throw new BenderDatabaseException(print_r($pdo->errorInfo(),true));
    $schema = array();
    foreach($st as $table)
    {
            $tableName = $table['Tables_in_' . $dbName];
            $objectName = Formatter::underscoreToUpperCamelCase($tableName, '_', true);
            
            $dbTable = new BenderTable(array('object' => $tableName, 'table' => $tableName));
            $dbTable->initialize($objectName);
            
            $dbFields = array();
            
            $fields = $dbTable->getFields();
            
            while ($fields->valid())
            {
              $field = $fields->current();
              $dbFields[ $field->getName() ] = array(
                'type' => $field->getBaseDataType()
              );
              $fields->next();
            }
            if(!BenderRequest::getInstance()->getFlag('no-fields'))
               $schema[$objectName] = array('table' => $tableName, 'extends' => false,'fields' => $dbFields);
            else
               $schema[$objectName] = array('table' => $tableName, 'extends' => false);
    }
    $schema = array('schema' => $schema);
    $yaml = sfYaml::dump($schema,4);
    $fs = new FileSaver();
    $fs->setOutputDir('application/config');
    $fs->saveFile('generated.schema.yml',$yaml);
    
  }

}
